import { _decorator, Button, Color, color, Component, instantiate, Label, Node, Prefab, Sprite, SpriteFrame, Toggle } from 'cc';

import { Core } from '../Core/Core';
import { ResourceManager } from '../Core/ResourceManager';
import { EEvent, EPath, ESubView, EView } from '../Config/Enum';
import { EItemQuality, EItemType, IItem, ItemQualityColors } from '../Item/Item';
import { BagItem } from '../Item/BagItem';
import { PrefabPath } from '../Config/ResourceConfig';
import { Equipment, IEquipment } from '../Item/Equipment';
import { Util } from '../Util';
import { MAX_QUIPMENT_LEVEL } from '../Config/Config';


const { ccclass, property } = _decorator;

@ccclass('ForgeView')
export class ForgeView extends Component {
        // 添加定时器引用
    private refreshTimer: number = 0;

    ndBG: Node = null!; // 背景节点
    ndShaixuan: Node = null!; // 筛选节点


    //ndShopItemDetail:Node
    btnBag: Button = null!; // 背包按钮组件
    btnShop: Button = null!; // 商店按钮组件
    btnForge: Button = null!; // 锻造按钮组件

    shopItems: IItem[] = []; // 商店物品列表

    lbNumOfItems: Label = null!; // 背包物品数量标签
    lbRefreshTime: Label = null!; // 刷新时间标签

    // Forge
    ndAffixParent: Node;
    ndForgeBagItem: Node;
    equipment_forge: Equipment;
    private forgeItems: IEquipment[] = []; // 存储当前类型的装备物品列表
    lbAPDP_forge: Label;
    value_forge: number;

    

    protected onLoad(): void {
  
        //Forge
        this.ndAffixParent = this.node.getChildByName("Board").getChildByName("Affixes");
        this.ndForgeBagItem = this.node.getChildByName("Board").getChildByName("Icon").getChildByName("BagItem");
        this.equipment_forge = null!;
        this.lbAPDP_forge = this.node.getChildByName("Board").getChildByName("APDP").getComponent(Label);
        this.value_forge = null!;

    }

    protected onEnable(): void {

        Core.Instance.event.on(EEvent.OpenForgeView, this.onButtonOpenForge, this);
        Core.Instance.currentView = EView.ArsenalView;


    }

    protected onDisable(): void {
        Core.Instance.event.off(EEvent.OpenForgeView, this.onButtonOpenForge, this);
        Core.Instance.currentSubView = null

    }



    //////////////////////////// 锻造 ////////////////////////////
    onButtonOpenForge(){
        console.log("初始化背包");
        Core.Instance.currentSubView = ESubView.Forge;


        Core.Instance.lastOpenArsenal = "Forge"

        this.initBagItem(ESubView.Forge);

        console.log("当前锻造装备this.equipment_forge:", this.equipment_forge);
        console.log("当前锻造装备Core.Instance.currentItem:", Core.Instance.currentItem);

        // 把当前装备加载到锻造界面
        // if(Core.Instance.currentItem){
        //     let index = Core.Instance.bag.getItems().indexOf(Core.Instance.currentItem)
        //     console.log("当前锻造装备index:", index);
        //     if(index!=-1){
        //         this.onButtonLoadItemToForge(index+1);
        //     }
        // }

        this.onButtonLoadItemToForge();


    }

    initBagItem(ndName:ESubView=ESubView.Bag){
        this.createBagItem(ndName); // 创建所有背包格子
        const bagItems = Core.Instance.bag.getItems();

        const contentNode = this.node.getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        
        // 遍历所有背包格子并初始化
        for (let i = 0; i < contentNode.children.length; i++) {
            const bagItemNode = contentNode.children[i];
            const bagItemComp = bagItemNode.getComponent(BagItem);
            
            if (i < bagItems.length) {
                // 初始化有物品的格子
                bagItemComp.init(bagItems[i]);
                bagItemNode.active = true;
            } else {
                // 保持空格子显示（但无物品）
                //bagItemComp.init(null); // 初始化为空状态
            }
        }

    }

        // 创建背包格子
    createBagItem(ndName:ESubView=ESubView.Bag) {
        console.log("创建背包格子节点");
        // 获取内容容器节点
        const contentNode = this.node.getChildByName(ndName).getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        
        // 清除现有节点（可选，根据需求决定）
        contentNode.removeAllChildren();
        
        // 获取BagItem预制体
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.BagItem) as Prefab;
        console.log("BagItem 预制体:", prefab);
        
        // 创建指定数量的背包格子
        for (let i = 0; i < Core.Instance.maxBag; i++) {
            const bagItemNode = instantiate(prefab);
            bagItemNode.name = `BagItem${i + 1}`; // 设置名称：BagItem1, BagItem2...
            contentNode.addChild(bagItemNode);
        }
    }


    unloadCurrentItem() {
        console.log("卸载当前装备信息 unloadCurrentEquipment");
        // 清除当前装备信息
        this.ndForgeBagItem.destroy()
        //this.lbDesc_current.string = ""; // 清除描述
        //this.lbName_current.string = ""; // 清除名称
        //this.lbProfession_current.string = ""; // 清除职业限制
        this.lbAPDP_forge.string = ""; // 清除APDP

        this.ndAffixParent.children.forEach(node => node.active = false); // 隐藏所有词缀节点

        //this.ndWuxingAffixParent_current.children.forEach(node => node.active = false); // 隐藏所有五行词缀节点
    }

    onButtonLoadItemToForge(){
        if (!Core.Instance.currentItem) return;
        // this.unloadCurrentItem(); // 清除之前的装备信息
        // console.log("锻造装备onButtonLoadItemToForge加载装备信息,选择的装备格子:", value);
        // console.log("锻造装备onButtonLoadItemToForge currentITem", Core.Instance.currentItem);
        // this.value_forge = value;
        this.unloadCurrentItem(); // 清除之前的装备信息
        // this.forgeItems=Core.Instance.bag.getEquipmentItems()

        // let num = Util.extractNumberFromEnd(value)-1
        // console.log("加载装备信息,选择的装备格子num:", num);
        // this.equipment_forge = this.forgeItems[num] as Equipment;
        // console.log("加载新装备信息,新装备:", this.equipment_forge);
        // if (!this.equipment_forge) {return}


        this.equipment_forge = Core.Instance.currentItem as Equipment;

        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.BagItem) as Prefab;
        const bagItemNode = instantiate(prefab);
        bagItemNode.setParent(this.node.getChildByName("Board").getChildByName("Icon"));
        bagItemNode.setPosition(0,0);
        bagItemNode.getComponent(BagItem).init(this.equipment_forge);


        // 显示物品描述
        // this.lbDesc_new.string = this.newEquipment.desc || "无描述";
        // this.lbName_new.string = this.newEquipment.name || "无名称";
        // this.lbProfession_new.string = this.showProfessionRestrictions(this.newEquipment)

        // 显示APDP
        if(this.equipment_forge.ap === 0){
            this.lbAPDP_forge.string = `防御力: ${this.equipment_forge.dp}`;
        }else{
            this.lbAPDP_forge.string = `攻击力: ${this.equipment_forge.ap}`;
        }

        // 显示词缀
        if (this.equipment_forge.itemType === EItemType.Equipment || this.equipment_forge.itemType === EItemType.Gem) {
            this.showAffixes(this.equipment_forge, this.ndAffixParent);
            //this.showWuxingAffixes(this.newEquipment, this.ndWuxingAffixParent_new);
        }



        //this.ndButton.active = true; // 显示按钮
        


    }

    private showAffixes(equipment: IEquipment, affixParent): void {
        // 隐藏所有词缀节点
        affixParent.children.forEach(node => node.active = false);
        
        // 显示当前装备的词缀
        if (equipment.affixes && equipment.affixes.length > 0) {
            for (let i = 0; i < equipment.affixes.length; i++) {
                const affixNode = affixParent.children[i];
                if (affixNode) {
                    affixNode.getComponent(Label).string = equipment.affixes[i].description;
                    affixNode.active = true;
                }
            }
        }
    }

    
    onButtonStrengthen(){
        console.log("强化")
        // 获取当前装备
        console.log("当前锻造装备:", this.equipment_forge);
        const equipment = this.equipment_forge;
        if (!equipment) {
            console.log("没有选择装备");
            return;
        }
        // 检查是否可以强化
        // 检查等级
        if (equipment.level >= MAX_QUIPMENT_LEVEL) {
            Core.Instance.showTips("装备已达最高等级，无法强化！");
            return;
            
        }
        // 检查cost
        if (equipment.getStrengthenCost() > Core.Instance.gold) {
            Core.Instance.showTips("铜钱不足，无法强化！");
            return;
            
        }
        // 可以强化
        let result = equipment.strengthen();
        if (result) {
            Core.Instance.showTips("装备强化成功！");
            // 更新显示
            this.initBagItem(ESubView.Forge);
            this.onButtonLoadItemToForge();
        }
    }



}